package com.pipayshop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pipayshop.entity.UserShopInfo;
import com.pipayshop.entity.RechargePermissionsOrder;
import com.pipayshop.entity.UserInfo;
import com.pipayshop.exception.BusinessException;
import com.pipayshop.mapper.UserAccountInfoMapper;
import com.pipayshop.mapper.ItemInfoMapper;
import com.pipayshop.mapper.RechargePermissionsOrderMapper;
import com.pipayshop.mapper.UserInfoMapper;
import com.pipayshop.service.RechargePermissionsOrderService;
import com.pipayshop.service.UserAccountInfoService;
import com.pipayshop.utils.StringUtil;
import com.pipayshop.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zxb
 * @since 2023-08-06
 */
@Service
public class RechargePermissionsOrderServiceImpl extends ServiceImpl<RechargePermissionsOrderMapper, RechargePermissionsOrder> implements RechargePermissionsOrderService {

    @Resource
    RechargePermissionsOrderMapper rechargePermissionsOrderMapper;

    @Resource
    private UserAccountInfoService accountInfoService;

    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    ItemInfoMapper itemInfoMapper;

    private final String MESSAGE = "order_already_paid";


    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addShopSum(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            throw new BusinessException("invalid_parameter");
        }
        RechargePermissionsOrder data = rechargeComplete(orderId);
        // 增加实体店绑定数
        int update1 = userInfoMapper.update(null, new UpdateWrapper<UserInfo>()
                .eq("uid", data.getUid())
                .eq("status", 0)
                .setSql("shop_balance = shop_balance +" + data.getPermissionsCount()));
        if (update1 < 1) {
            throw new BusinessException("increase_store_bindings_failed");
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUploadBalanceInfo(String orderId) {
        if (StringUtils.isEmpty(orderId)) {
            throw new BusinessException("invalid_parameter");
        }
        RechargePermissionsOrder data = rechargeComplete(orderId);
        // 更改可上架商品数值
        int update1 = itemInfoMapper.update(null, new UpdateWrapper<UserShopInfo>()
                .eq("uid", data.getUid())
                .setSql("shop_upload_balance = shop_upload_balance +" + data.getPermissionsCount()));
        if (update1 < 1) {
            throw new BusinessException("update_max_shelf_items_failed");
        }
        return true;
    }

    /**
     * 生成未支付订单
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getUploadBalanceNoPayOrder(String token) {
        String orderId = StringUtil.generateShortId();
        Claims dataFromToken = TokenUtil.getDataFromToken(token);
        String uid = dataFromToken.get("uid", String.class);
        Integer permissionsCount = dataFromToken.get("permissionsCount", Integer.class);
        Integer chargeType = dataFromToken.get("chargeType", Integer.class);
        if (StringUtils.isEmpty(uid) || permissionsCount == null || chargeType == null) {
            throw new BusinessException("invalid_parameter");
        }
        BigDecimal transactionAmount = BigDecimal.valueOf(Double.parseDouble(dataFromToken.get("transactionAmount", String.class)));

        if (transactionAmount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new BusinessException("amount_must_be_greater_than_zero");
        }

        RechargePermissionsOrder order = new RechargePermissionsOrder(null, orderId, uid, permissionsCount,
                transactionAmount, null, null, null, chargeType);
        // 生成订单
        int insert = rechargePermissionsOrderMapper.insert(order);
        if (insert < 1) {
            throw new BusinessException("recharge_balance_unpaid_order_failed");
        }
        return orderId;
    }

    /**
     * 两个下单操作的共用类
     */
    @Transactional(rollbackFor = Exception.class)
    public RechargePermissionsOrder rechargeComplete(String orderId) {
        // 校验订单id是否已经存在，保证接口的幂等性，避免重复下单
        RechargePermissionsOrder data = rechargePermissionsOrderMapper.selectOne(new QueryWrapper<RechargePermissionsOrder>()
                .eq("order_id", orderId));
        if (data == null || data.getStatus() == 1) {
            throw new BusinessException(MESSAGE);
        }
        // 扣减余额积分
        accountInfoService.reduceAccount(data.getUid(), data.getTransactionAmount());

        // 修改未支付订单的状态
        int update2 = rechargePermissionsOrderMapper.update(null, new UpdateWrapper<RechargePermissionsOrder>()
                .eq("order_id", data.getOrderId())
                .set("status", 1));
        if (update2 < 1) {
            throw new BusinessException("order_status_modification_failed");
        }
        return data;
    }
}
